package server;

import server.mapper.Context;
import server.mapper.Host;
import server.mapper.Mapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            HttpServlet httpServlet = this.getHttpServlet(request);
            if (httpServlet == null)
            {
                response.outputHtml(getAppBaseUrl(request), request.getUrl());
            }
            else{
                // 动态资源servlet请求
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *获取servlet
     * @return
     */
    private HttpServlet getHttpServlet(Request request) {
        HttpServlet httpServlet = null;
        //获取hostMap,根据请求的请求路径获取到对于Host
        Map<String, Host> hostMap = mapper.getHostMap();
        Host host = hostMap.get(request.getHost());
        if (host != null)
        {
            // /demo1/lagou
            String requestUrl = request.getUrl();
            requestUrl = requestUrl.substring(1);
            int pos = requestUrl.indexOf("/");
            if (pos > 0)
            {
                // demo1
                String contextUrl = requestUrl.substring(0, pos);
                // /lagou
                String servletUrl = requestUrl.substring(pos);
                Map<String, Context> contextMap = host.getContextMap();
                Context context = contextMap.get(contextUrl);
                if (context != null)
                {
                    Map<String, HttpServlet> wrapperServletMap = context.getWrapperServletMap();
                    httpServlet = wrapperServletMap.get(host.getAppBase() + "/" + contextUrl + servletUrl);
                }
            }
        }
        return httpServlet;
    }

    private String getAppBaseUrl(Request request) {
        Map<String, Host> hostMap = mapper.getHostMap();
        Host host = hostMap.get(request.getHost());
        if (host != null)
        {

            return host.getAppBase();
        }
        return "";
    }

}
